package server

import (
	models "fileshare/controller/modles"
	"fileshare/sqlconn"
	"fileshare/utils"
	"io"
	"mime/multipart"
	"os"
	"time"
)

/**
* @program: fileshare
*
* @description:
*
* @author: Koco.Allien
*
* @create: 2020-04-05 17:51
**/

//GetPublicFiles 返回用户分享的公共文件和公共文件
func GetPublicFiles() []models.BelongInfo {
	var files []models.BelongInfo
	sqlconn.MyDB.Model(models.BelongInfo{}).Where("to_userid in (?)", []int{0, 1}).
		Where("code=? AND share_url =? ", "", "").
		Not("id = ? ", 1).
		Order("create_at desc").Find(&files)
	return files
}

//保存到本地
func SaveFileTolocal(fpath string, fi multipart.File) {
	f, _ := os.Create(fpath)
	defer f.Close()
	defer fi.Close()
	_, _ = io.Copy(f, fi)
}

//存储到数据库
func SaveFileToDB(uid int, filename string, fpath string, touid int, root int, isfile bool) {
	var user models.UserInfo
	user.ID = uid
	sqlconn.MyDB.Find(&user)

	belong := models.BelongInfo{
		UID:        uid,
		CreateAt:   time.Now().Local(),
		UpdateAt:   time.Now().Local(),
		FFname:     filename,
		UName:      user.Name,
		FPath:      fpath,
		Isfolder:   isfile,
		ToUserid:   touid,
		ToUserName: GetUser(touid).Name,
		ShareUrl:   "",
		Code:       "",
		Root:       root,
	}
	sqlconn.MyDB.Create(&belong)
}

//通过信息查找到belong信息
func GetBelongInfo(id, uid int, code string) *models.BelongInfo {
	utils.MsgToLog("查询文件的信息:", id, uid, code)
	bf := &models.BelongInfo{}
	sqlconn.MyDB.Model(models.BelongInfo{}).Where("id=? AND to_userid = ? AND code=? ", id, uid, code).First(bf)
	utils.MsgToLog("查询文件的结果:", bf.FFname)
	return bf

}

//删除文件
func DelFile(fid int) {
	sqlconn.MyDB.Delete(&models.BelongInfo{ID: fid})
}

// Updatefile 更新文件的信息
func Updatefile(f *models.BelongInfo) error {
	return sqlconn.MyDB.Model(&models.BelongInfo{}).Update(f).Error
}
